package vcp.server.deamontasks;

import java.util.List;
import java.util.TimerTask;

import ocsf.server.ConnectionToClient;
import vcp.entity.User;
import vcp.server.DAO.UserDAO;
import vcp.server.interfaces.IServer;
/** 
 * 
 * @author VCP team
 *class verifies logged in users and verifies status 
 */
public class UserDBCleanUpTask extends TimerTask
{
	private final IServer server;
	/**
	 * class constructor
	 * @param vcpServer
	 */
	public UserDBCleanUpTask ( IServer vcpServer )
	{
		this.server = vcpServer;
	}

	@Override
	public void run ()
	{
		synchronized (this.server.getDBLock())
		{
			UserDAO userDAO = new UserDAO();
			List <User> users = userDAO.findAllLoggedIn();

			// find logged in users
			if ( users != null )
			{
				for ( User user : users )
				{
					boolean foundLoggedIn = false;

					// run through all connection & verify if specific user is
					// indeed connected
					for ( ConnectionToClient connection : this.server.getConnections() )
					{
						Integer userID = (Integer) connection.getInfo(User.class.toString());
						foundLoggedIn = userID != null && userID == user.getUserID();
						if ( foundLoggedIn )
						{
							break;
						}
					}

					// if not connected, set isLoggedIn column in user to false;
					if ( ! foundLoggedIn )
					{
						System.out.println("User " + user.getUserID() + " was cleared");
						userDAO.updatedLoggedInStatus(user.getUserID(), foundLoggedIn);
					}
				}
			}
		}
	}

}
